package com.holi.hiteacher.data;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.holi.hiteacher.bean.EmailBean;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;
import java.util.Date;

/**
 * @description:
 * @author: JoshuaWong E-mail:joshuawongchn@gmail.com
 * @date: 2017年01月05日 17:48
 * @version: 1.0
 */
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
    private static final String DATABASE_NAME = "hiteacher.db";
    private static final int DATABASE_VERSION = 1;

    private static RuntimeExceptionDao<EmailBean, Integer> emailDao = null;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, com.j256.ormlite.support
            .ConnectionSource connectionSource) {
        try {
            TableUtils.createTable(connectionSource, EmailBean.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        // create some entries in the onCreate
        for (int i = 0; i < 10; i++) {
            EmailBean bean = new EmailBean();
            bean.setFrom("系统信息");
            bean.setTime(new Date());
            bean.setTitle("成绩提示");
            bean.setContent("【成绩提示】 你 工程数值方法 考试成绩为 81.00 ");
            bean.setReaded(false);
            getEmailDao().create(bean);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, com.j256.ormlite.support
            .ConnectionSource connectionSource, int i, int i1) {
        try {
            TableUtils.dropTable(connectionSource, EmailBean.class, true);
            onCreate(db, connectionSource);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public RuntimeExceptionDao<EmailBean, Integer> getEmailDao() {
        if (emailDao == null) {
            emailDao = getRuntimeExceptionDao(EmailBean.class);
        }
        return emailDao;
    }

    @Override
    public void close() {
        super.close();
        emailDao = null;
    }
}
